<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head th:include="template::head">

</head>
<body class="sidebar-mini sidebar-collapse ng-cloak" ng-app="ESL" style="min-width: 1200px">
<div class="wrapper" ng-controller="esl_manager">
    <!-- Navbar -->
    <header th:include="template::header"></header>
    <!-- Content Wrapper. Contains page content -->
    <div class="content-wrapper">
        <!-- Content Header (Page header) -->
        <section class="content-header">
            <div class="container-fluid">
                <div class="row mb-2">
                    <div class="col-sm-6">
                        <h1 th:text="#{menu_esl_manager}">标签管理</h1>
                    </div>
                    <div class="col-sm-6">
                        <ol class="breadcrumb float-sm-right">
                            <li class="breadcrumb-item"><a href="#">Home</a></li>
                            <li class="breadcrumb-item active" th:text="#{menu_esl_manager}">标签管理</li>
                        </ol>
                    </div>
                </div>
            </div><!-- /.container-fluid -->
        </section>

        <!-- Main content -->
        <section class="content">
            <div class="row">
                <div class="col-12">

                    <!-- /.card -->

                    <div class="card">
                        <div class="card-header">

                            <div class="row">
                            <!--<textarea id="message"  readonly="true" style="width:400px;height:200px;float:right" ></textarea>-->


                            <!--<div class="col-md-6">-->
                                <!--<p style="margin-bottom:0;"><b>手动输入绑定</b></p>-->
                                <!--<span>商品编码:</span><input type="text" placeholder="输入商品编码" ng-model="menu_cmmdtCode"/>-->
                                <!--<span>门店编码:</span><input type="text" placeholder="输入门店编码" ng-model="menu_storeCode"/>-->
                                <!--<input class="btn btn-sm  btn-success" type="button" value="手动输入绑定" ng-click="menuBinding()"/>-->
                            <!--</div>-->

                            <div sec:authorize="hasRole('ROLE_ADMIN')" class="col-md-5">
                                <p style="margin-bottom:0;" th:text="#{esl_manager_bsIp}">基站ID:</p>
                                <select id="networkIP" ng-model="networkIP" class="form-control select2" style="width:60%">
                                    <option ng-repeat="ip in networkipList" value="{{ip}}">{{ip}}</option>
                                </select>

                                <input class="btn btn-sm btn-primary" type="button" th:value="#{esl_manager_reset_channel}" ng-click="send_p8()"
                                       data-toggle="tooltip" data-placement="top" title="使基站重新选择信道"/>
                                <input class="btn btn-sm btn-primary" type="button" th:value="#{esl_manager_esl_login}" ng-click="send_p9()"
                                       data-toggle="tooltip" data-placement="top" title="点击后30分钟左右，所有基站范围内的价签将重新登录"/>
                            </div>
                        <div>
                            <p>屏幕尺寸</p>
                            <select ng-model="demoInch">
                                <option value="42">4.2寸</option>
                                <option value="29">2.9寸</option>
                            </select>
                            <input class="btn btn-sm btn-primary" type="button" th:value="下发测试图片" ng-click="refreshDemo()" />
                        </div>

                        <p>
                            <ul ng-repeat="ip in networkipList">
                            <li style="float:left;margin-right: 50px">
                                {{ip}}
                                <i class="fa fa-circle" style="color:green"></i>
                                <strong >connected</strong>

                            </li>
                        </ul>
                        </p>
                        </div>
                        </div>
                        <!-- /.card-header -->
                        <div class="card-body">
                            <h4 th:text="#{esl_manager_list}">价签信息列表</h4>
                            <div >
                                <input type="text" id="networkIP_search" ng-model="search.networkIP" th:placeholder="#{esl_search_networkIP}"/>
                                <input type="text" id="tinyIP_search" ng-model="search.tinyIP" th:placeholder="#{esl_search_tinyIP}"/>
                                <input type="text" id="storeCode_search" ng-model="search.storeCode" th:placeholder="门店编码"/>
                                <input type="text" id="gidIndex_search" ng-model="search.gidIndex" th:placeholder="gid_index"/>
                                <input type="text" id="versionStr_search" ng-model="search.versionStr" th:placeholder="#{esl_manager_version}"/>
                                <button ng-click="loadItems()" class="btn btn-sm  btn-primary" th:text="#{action.search}">查询</button>
                                <button ng-click="reset()" class="btn btn-sm btn-primary">重置</button>
                                <button sec:authorize="hasRole('ROLE_ADMIN')" ng-click="refresh()" class="btn btn-sm btn-warning">刷新价签</button>
                                <button sec:authorize="hasRole('ROLE_ADMIN')" ng-click="openRemovePopup1()" class="btn btn-sm  btn-danger" th:text="#{action.delete}">删除</button>
                            </div>
                            <div class="table-responsive">
                            <table id="tab1" class="table table-bordered table-hover table-condensed  " >
                                <thead>
                                <tr>
                                    <th><input type="checkbox"  ng-model="selectAll"  ng-change="changeAll()"/></th>
                                    <th></th>
                                    <th style="white-space: nowrap;" ><i id="id_sort_icon_networkIP" class="fa fa-fw fa-sort" ng-click="sortBy('networkIP')"></i><span th:text="#{esl_search_networkIP}"></span></th>
                                    <th style="white-space: nowrap;" ><i id="id_sort_icon_tinyIP" class="fa fa-fw fa-sort" ng-click="sortBy('tinyIP')"></i><span th:text="#{esl_manager_tinyIP}"></span></th>
                                    <th style="white-space: nowrap;" ><i id="id_sort_icon_storeCode" class="fa fa-fw fa-sort" ng-click="sortBy('storeCode')"></i><span th:text="#{esl_manager_storeCode}"></span></th>
                                    <th style="white-space: nowrap;" ><i id="id_sort_icon_gidIndex" class="fa fa-fw fa-sort" ng-click="sortBy('gidIndex')"></i><span th:text="GID_Index"></span></th>


                                    <th style="white-space: nowrap;" data-toggle="tooltip" data-placement="top"
                                        title="推送数据到价签的次数，无色表示无推送任务或价签更新成功,
                                        <span style='color:yellow'>黄色</span>表示数据推送中，<span style='color:red'>红色</span>表示推送失败">
                                        <i id="id_sort_icon_downloadTimes" class="fa fa-fw fa-sort" ng-click="sortBy('downloadTimes')"></i><span th:text="#{esl_manager_downloadTimes}"></span> </th>

                                    <th style="white-space: nowrap;" ><i id="id_sort_icon_pushTimes" class="fa fa-fw fa-sort" ng-click="sortBy('pushTimes')"></i><span th:text="推送中"></span></th>
                                    <th style="white-space: nowrap;" ><i id="id_sort_icon_defaultPageId" class="fa fa-fw fa-sort" ng-click="sortBy('defaultPageId')"></i><span th:text="默认图片id"></span></th>
                                    <th style="white-space: nowrap;" ><i id="id_sort_icon_downloadDateTime" class="fa fa-fw fa-sort" ng-click="sortBy('downloadDateTime')"></i><span th:text="#{esl_manager_pushTime}"></span> </th>
                                    <th style="white-space: nowrap;" ><i id="id_sort_icon_feedbackTime" class="fa fa-fw fa-sort" ng-click="sortBy('feedbackTime')"></i><span th:text="价签反馈时间"></span> </th>
                                    <th style="white-space: nowrap;" ><i id="id_sort_icon_versionStr" class="fa fa-fw fa-sort" ng-click="sortBy('versionStr')"></i><span th:text="#{esl_manager_version}"></span> </th>
                                    <th style="white-space: nowrap;" th:text="#{action.operation}"></th>
                                    <!--<th></th>-->
                                </tr>
                                </thead>
                                <tbody>

                                <tr ng-repeat="esl in eslList" ng-click="changeCurrents(esl,$event)">

                                    <td>
                                        <label>
                                            <input type="checkbox" value="{{esl.tinyIP}}" ng-model="esl.checked" name="checkbox" ng-click="changeCurrent(esl,$event)"/>
                                        </label>
                                    </td>

                                    <td>{{$index+1}}</td>
                                    <td>{{esl.networkIP}}</td>
                                    <td>{{esl.tinyIP}}</td>
                                    <td>{{esl.storeCode}}</td>
                                    <td>{{esl.gidIndex}}</td>
                                    <td class="{{esl.downloadTimes>0?esl.downloadTimes>=6?'bg-danger text-white':'bg-warning text-white':''}}">{{esl.downloadTimes}}</td>
                                    <td>{{esl.pushTimes}}</td>
                                    <td>{{esl.defaultPageId}}</td>
                                    <td>{{esl.downloadDateTime|date:'yyyy-MM-dd HH:mm:ss'}}</td>
                                    <td>{{esl.feedbackTime|date:'yyyy-MM-dd HH:mm:ss'}}</td>
                                    <td>{{esl.versionStr}}</td>
                                    <td style="white-space: nowrap;"><button class="btn btn-sm btn-success" th:text="#{action.spread}" ng-click="spreadData(esl,$index,$event)"></button>
                                    </td>
                                </tr>

                                </tbody>

                            </table>
                            </div>

                            <!--额外数据 -->
                            <template id="extraTr">
                                    <tr id="trId"><td colspan="num">
                                    <ul style="display:inline-block">
                                        <li>screenSize</li>
                                        <li>dpi</li>
                                        <li>screenColor</li>
                                        <li>freezer</li>


                                    </ul>
                                    <ul style="display:inline-block">
                                        <li>batLevel</li>
                                        <li>RSSI_val</li>
                                        <li>heartBeat</li>
                                        <li>lastHeartbeatTime</li>
                                    </ul>
                                        <ul style="display:inline-block">
                                            <li>firmwareId</li>
                                            <li>led</li>
                                            <li>mpd</li>
                                            <li>maxPages</li>
                                        </ul>
                                    </td></tr>
                            </template>
                            <navigation th:include="template::page"></navigation>
                        </div>

                    </div>

                    <!-- /.card-body -->
                </div>
                <!-- /.card -->
            </div>
            <!-- /.col -->
            <!-- /.row -->
            <div class="modal fade" id="remove_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
                <div class="modal-dialog modal-sm" role="document" style="margin-top:300px;">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h4 class="modal-title" id="id_remove_modal_title" th:text="#{sku.removeAlertMsg}"></h4>
                            <input type="hidden" id="id_remove_modal_title_hidden" th:value="#{sku.removeAlertMsg}" />
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-default" data-dismiss="modal" th:text="#{action.close}"></button>
                            <button type="button" class="btn btn-primary" ng-click="deleteEsl()" th:text="#{action.confirm}"></button>
                        </div>
                    </div>
                </div>
            </div>

        </section>
        <!-- /.content -->



    </div>
    <!-- /.content-wrapper -->
    <footer th:include="template::footer"></footer>


</div>
<!-- ./wrapper -->



</body>
<navigation th:include="template::js"></navigation>
<script th:src="@{/plugins/select2/select2.full.min.js}"></script>
<script th:inline="javascript">

    $(function(){
        $('.select2').select2()
         $("[data-toggle='tooltip']").tooltip({html : true });
    })

    var top_page=[[#{page.top_page}]]
    var previous_page= [[#{page.previous_page}]]
    var next_page= [[#{page.next_page}]]
    var tail_page=[[#{page.tail_page}]]
    var eslApp=angular.module('ESL',[])
    var websocket = null;
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        var protocol=document.location.protocol;
        if('http:'==protocol){
            websocket = new WebSocket("ws://"+window.location.host+"/client/websocket");
        }else {
            websocket = new WebSocket("wss://"+window.location.host+"/client/websocket");
        }

        eslApp.value('websocket',websocket)
    }
    else {
        alert('Not support websocket')
    }
    eslApp.controller('esl_manager',function ($scope,$http,websocket,$timeout) {

        // var token = ${_csrf.token} ;
        $scope.menu={"esl":true,"sku":false} //记录当前页面对应的菜单
        $scope.search ={};
        $scope.skuList=[]
        $scope.eslList=[]
        $scope.storeList=[]
        $scope.count = 0;//已选择数量
        //点击单个checkbox
        $scope.changeCurrent = function(current, $event) {
            // //计算已选数量 true加， false减
            $scope.count += current.checked ? 1 : -1;
            //判断是否全选，选数量等于数据长度为true
            $scope.selectAll = $scope.count=== $scope.eslList.length;
            //


            $event.stopPropagation();//阻止冒泡

        };



        //单击行选中
        $scope.changeCurrents = function(current, $event) {
            if(current.checked == undefined){
                current.checked = true;
            }else{
                current.checked = !current.checked;
            }
            $scope.changeCurrent(current, $event);
        };

        //全选（取消全选
        $scope.changeAll = function() {
            angular.forEach($scope.eslList, function(item) {
                item.checked = $scope.selectAll;
            });
            $scope.count = $scope.selectAll ? $scope.eslList.length : 0;

        };



        $scope.gotoPage = function(page) {

            if(page!=0&&!page||page<0||page==$scope.pagination.number||page>=$scope.pagination.totalPages){
                return;
            }

            $scope.page = page;
            $scope.loadItems();

        }
        $scope.changeSize = function() {
            $scope.page =0
            $scope.loadItems();
        }


        pagingScope($scope,{'downloadTimes':true})


        $scope.init=function (){

            $http({
                url:"/esl_rest/find_all"
            }).success(function (map) {
                $scope.networkipList=map.networkIPs;
                $scope.sortBy("downloadTimes")  //根据downloadTime排序
            }).
            error(function (msg) {
                alert(msg)
            })
        }

        $scope.loadItems = function(){
            $http({
                url:"/esl_rest/eslTab/listByPage",
                data:{page : $scope.page, size : $scope.size, sortStr : $scope.sort, sortAscOrDesc : $scope.sortAscOrDesc, 'searchObj' : JSON.stringify($scope.search)},
                method:"post",
                // headers:{'X-CSRF-TOKEN': token,'Content-Type': 'application/x-www-form-urlencoded'},
                headers:{'Content-Type': 'application/x-www-form-urlencoded'},
                transformRequest: function(obj) {
                    var str = [];
                    for (var s in obj) {
                        str.push(encodeURIComponent(s) + "=" + encodeURIComponent(obj[s]));
                    }
                    return str.join("&");
                }
            }).success(function (json) {
                $scope.eslList = json.content;
                $scope.pagination = getPagination(json, $scope.page);
                $scope.selectAll=false;
                $scope.count=0;

            }).
            error(function (msg) {
                alert(msg.message)
            })

        }
        $scope.init()


        $scope.deleteEsl=function () {
                $scope.deleteSelect()
        }

        $scope.deleteSelect=function () {

            $http({
                url:"/esl_rest/delete_esl",
                params:{"eslIds":$scope.eslIds},
            }).success(function (result) {
                $scope.loadItems()
                angular.element("#remove_modal").modal("hide");
                alertSuccess()
            }).
            error(function (msg) {
                alert(msg.message)
            })
        }


        $scope.openRemovePopup1 = function() {
            $scope.eslIds=[]
            var i=0;
            $("table :checkbox[name='checkbox']").each(function () {
                if($(this).prop("checked")){
                    $scope.eslIds[i++]=($(this).val())
                }
            })
            if(!$scope.eslIds.length) {
                alert([[#{esl_manager_deleteAlert_esl}]])
                return 0;
            }
            $("#id_remove_modal_title").html(($("#id_remove_modal_title_hidden").val() + ""));
            angular.element("#remove_modal").modal("show");


        }


        $scope.refresh=function () {

            var eslIds=[]
            var i=0;
            $("table :checkbox[name='checkbox']").each(function () {
                if($(this).prop("checked")){
                   eslIds[i++]=($(this).val())
                }
            })
            if(!eslIds.length) {
                alert([[#{esl_manager_deleteAlert_esl}]])
                return 0;
            }
            $http({
                url:"esl_rest/refresh",
                params:{"eslIds":eslIds}
            }).success(function (json){
                if(json){
                    alert(json.errmsg);
                    $scope.loadItems();
                    return;
                }
                $scope.loadItems();
                alertSuccess()

            }).error(function (msg) {
                alert(msg.message)
            })
        }



        //展开esl行，显示更多数据
        $scope.spreadData=function (esl,$index,$event) {
            $event.stopPropagation()
            if($("#trId"+$index).html()){
                $("#trId"+$index).remove();
                return 0;
            }
            var thisTr=$($event.target).parent().parent()
            var extraTr=$("#extraTr").html()
            var tdLen=thisTr[0].childElementCount
            var rssi=esl.rssiVal
            var firmware=esl.eslFirmware
            var s=extraTr.replace("screenSize","屏幕尺寸：" +firmware.screen_size)
                .replace("batLevel",[[#{esl_manager_batLevel}]] +esl.eslStatus.battery)
                .replace("RSSI_val",[[#{esl_manager_rssi}]]+esl.eslStatus.rssiValue)
                .replace("dpi","分辨率："+firmware.dpi)
                .replace("screenColor","颜色："+firmware.screen_color)
                .replace("freezer","冷冻标签："+firmware.freezer)
                .replace("heartBeat","支持心跳："+firmware.heartbeat)
                .replace("maxPages","最大页数："+firmware.max_page_num)
                .replace("led","支持led："+firmware.led)
                .replace("mpd","支持多页："+firmware.mpd)
                .replace("firmwareId","固件ID: "+esl.firmwareId)
                .replace("lastHeartbeatTime","最后心跳时间:"+new Date(esl.eslStatus.lastUpdateTime).format("yyyy-MM-dd hh:mm:ss") )
                .replace("num",tdLen).replace("trId","trId"+$index)
            thisTr.after(s)
            $event.stopPropagation()
        }
        //rssi信号强度转换

        //屏幕尺寸转换
        function getLcdType(lcdType) {
            if(lcdType==3) lcdTypeStr="POP(9.6 cun)E-paper";
            else if(lcdType==4) lcdTypeStr="POP(5.1 cun)E-paper";
            else if(lcdType==5) lcdTypeStr="POP(5.1 cun)E-paper";
            else if(lcdType==48) lcdTypeStr="POP LCD";
            else if(lcdType==131) lcdTypeStr="2.9 ESL LCD";
            else if(lcdType==134) lcdTypeStr="2.9 single E-paper";
            else if(lcdType==140) lcdTypeStr="2.9 single E-paper";
            else if(lcdType==92) lcdTypeStr="2.9 ESL  E-paper";
            else if(lcdType==136) lcdTypeStr="2.13 ESL E-paper";
            else if(lcdType==142) lcdTypeStr="4.2 ESL E-paper";
            else if(lcdType==88) lcdTypeStr="2.13 ESL E-paper";
            else if(lcdType==90) lcdTypeStr="1.54 ESL E-paper";
            else if(lcdType==95) lcdTypeStr="2.2 ESL LCD";
            else lcdTypeStr=lcdType;
            return lcdTypeStr;
        }


        $scope.send_p8=function () {
            if(!$scope.networkIP) {
                alert([[#{networkIP_null_warning}]])
                return 0
            }
            $http({
                url:"/esl_rest/send_p8",
                params:{"networkIP":$scope.networkIP},
            }).success(function (msg) {
                // setMessageInnerHTML("send P8  AP："+$scope.networkIP+"----"+new Date().format("yyyy/MM/dd hh:mm:ss"))
                alertSuccess()
            }).error(function (msg) {
                alert(msg.message)
            })
        }
        $scope.send_p9=function () {
            if(!$scope.networkIP) {
                alert([[#{networkIP_null_warning}]])
                return 0
            }

            // var bsip=$("#networkIP option:selected").val()
            $http({
                url:"/esl_rest/send_p9",
                params:{"networkIP":$scope.networkIP},
            }).success(function (msg) {
                // setMessageInnerHTML("send P9  AP："+$scope.networkIP+"ESL relogin----"+new Date().format("yyyy/MM/dd hh:mm:ss"))
                alertSuccess()
            }).error(function (msg) {
                alert(msg.message)
            })
        }


        function getNewDate() {
            Date.prototype.format()
        }

        //查询当前账号下已连接的基站
        $scope.findNetworkIPList=function () {
            $http({
                url:"/esl_rest/find_networkIPList"
            }).success(function (map) {
                $scope.networkipList=map.networkIPs;
            })
        }
        //重置查询
        $scope.reset=function () {
            $scope.search={};
        };



        $scope.refreshDemo=function () {


            if(!$scope.demoInch){
                alert("demo图片尺寸不能位空")
                return;
            }

            var eslIds=[]
            var i=0;
            $("table :checkbox[name='checkbox']").each(function () {
                if($(this).prop("checked")){
                    eslIds[i++]=($(this).val())
                }
            })
            if(!eslIds.length) {
                alert([[#{esl_manager_deleteAlert_esl}]])
                return 0;
            }


            $http({
                url:"/esl_rest/demo_img",
                params:{eslIds:eslIds,"inch":$scope.demoInch}
            }).success(function () {
                $scope.loadItems()
            }).error(function (msg) {
                alert(msg.message)
            })
        }



        //webSocket begin


        //连接发生错误的回调方法
        websocket.onerror = function () {
            // setMessageInnerHTML("WebSocket connect error");
        };

        //连接成功建立的回调方法
        websocket.onopen = function () {
            // setMessageInnerHTML("WebSocket连接成功");
        }

        //接收到消息的回调方法
        websocket.onmessage = function (event) {

            var data=JSON.parse(event.data)
            var eslTab=data.obj;
            var date=new Date().format("yyyy/MM/dd hh:mm:ss")
            // if(data.cmd=='error'||data.cmd=='msg'){
            //     setMessageInnerHTML(data.msg+"---"+date);
            //     return;
            // }

            if(data.cmd=='ry'||data.cmd=='ey'){
                for(var i=0;i<$scope.eslList.length;i++){
                    if($scope.eslList[i].tinyIP==eslTab){
                        $scope.eslList[i].downloadTimes=0;
                        $scope.eslList[i].pushTime=0;
                        break;
                    }
                }
            }else if(data.cmd=='pushKa'){
                for(var i=0;i<$scope.eslList.length;i++){
                    if($scope.eslList[i].tinyIP==eslTab.tinyIP){
                        $scope.eslList[i]=eslTab;
                        break;
                    }
                }
            }else if(data.cmd=='apConnected'){   //基站建立连接
                $scope.findNetworkIPList()
            }else if(data.cmd=="apDisconnect"){   //基站断开
                var index=$scope.networkipList.indexOf(data.msg)
                if(index>-1){
                    $scope.networkipList.splice(index,1);
                }

            }


            $scope.$apply();
        }


        //连接关闭的回调方法
        websocket.onclose = function () {
            // setMessageInnerHTML("message window closed");
        }

        //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
        window.onbeforeunload = function () {
            closeWebSocket();
        }

        //将消息显示在网页上
        function setMessageInnerHTML(innerHTML) {
            return;
            if(document.getElementById('message'))
            document.getElementById('message').innerHTML = innerHTML + '\r\r'+document.getElementById('message').innerHTML;
        }

        //关闭WebSocket连接
        function closeWebSocket() {
            websocket.close();
        }

        //发送消息
        function send() {
            var message = document.getElementById('text').value;
            websocket.send(message);
        }
        //webSocket end



    });

</script>
</html>
